/**
 * Created by hsia on 2017/7/6.
 */
var InoutRecoder = function (targetObj) {
    this.targetObj = targetObj;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
InoutRecoder.prototype = {
    init: function () {
        var that = this;
        var fieldArray = this.sysUtils.getBindFieldArray(that.targetObj.find('.search-panel'));
        var functionArray = [
            {fName: 'search_btn', fs: this.findData},
            {fName: 'reset_btn', fs: this.resetInfo}
        ];
        this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        this.sysUtils.bindDoucment(this.models, this.targetObj, this);
        var sHeight = (this.targetObj.find('.search-panel')[0].clientHeight);
        var allHeight = (this.targetObj[0].clientHeight);
        this.targetObj.find('.dataList').height(allHeight-sHeight-2);
        this.initHtml();
        Utils.createDataDictDropDownList({
            div: this.targetObj.find('#credentialsType'),
            parentModelKey: BASIS.TRAFFIC_TYPE_CLASS.ROOT
        }, this);
        Utils.createDataDictDropDownList({
            div: this.targetObj.find('#inoutType'),
            parentModelKey: BASIS.IN_OUT_STATUS.ROOT
        }, this);
        Utils.createDataDictDropDownList({
            div: this.targetObj.find('#hasCorrected'),
            parentModelKey: BASIS.CORRECTIVE_PLATE.ROOT
        }, this);
        this.initTable();
        this.initOrz();
        this.findData();
    },
    initHtml:function(){
        this.userInfo = null;
        var that = this;
        var autoFlag = false;
        var selectFun = function(e){
            that.userInfo = this.dataItem(e.item);
            autoFlag = true;
        };
        var changeFun = function(e){
            if(!autoFlag){
                that.userInfo = null;
                that.targetObj.find("#operatorId").val("");
            }
            autoFlag = false;
        };
        this.sysUtils.autoCompleteUser("operatorId", "userName",selectFun,changeFun);
    },
    /*
     * 重置按钮
     */
    resetInfo:function(e){
        var that = $(e.target).data("that");
        that.sysUtils.setBindFieldNull(that.models.bindFieldArray);
        that.userInfo = null;
        that.targetObj.find("#operatorId").val("");
    },
    initTable : function() {
        var that = this;
        var columns = [
            {
                width : 30,
                headerTemplate : '<input type="checkbox" gridId="inoutRecordlist" onclick="gridCheckAll(this)" />',
                template : '<input type="checkbox" name="inoutRecord_template_id" value="${id}_${vehicleNo}_${recodeStatus}" />'
            },
            /*{
                title : '凭证编号',
                field : 'uniqueIdentifier'
            },*/
            {
                width : 100,
                title : '车牌号码',
                field : 'vehicleNo'
            },
           /* {
                title : '车辆颜色',
                field : 'carColor'
            },*/
            {
                width : 90,
                title : '凭证类型',
                template : '#:Utils.getModelNameByParentKey(BASIS.TRAFFIC_TYPE_CLASS.ROOT, data.credentialsType == null ? "" : data.credentialsType)#'
            },
            {
                width : 50,
                title : '状态',
                field : 'recodeStatus == 0 ? "入场":recodeStatus == 1?"出场":"作废"'
            },
            {
                width : 170,
                title : '进场时间',
                field : 'inTime'
            },
            /*{
                title : '进入区域',
                field : 'parInName'
            },*/
            {
                title : '进入工作站',
                field : 'wsnInName'
            },
            {
                title : '进场通道',
                field : 'chnInName'
            },
            {
                width : 170,
                title : '出场时间',
                field : 'outTime'
            },
            /*{
                title : '离开区域',
                field : 'parOutName'
            },*/
            {
                title : '出场工作站',
                field : 'wsnOutName'
            },
            {
                title : '出场通道',
                field : 'chnOutName'
            },

            {
                title : '收费人员',
                field : 'ouUname'
            },
            {
                width : 80,
                title : '缴纳金额',
                field : 'chargeMoney'
            }
        ];
        that.sysUtils.createGird(that.targetObj.find('#inoutRecordlist'), {
            selectable : 'single',
            autoSync : true,
            columnMenu : true,
            pageable : {input : true, numeric : false},
            columns : columns,
            change : function(e) {
                var selected = $.map(this.select(), function(itm) {
                    return $(itm).find('input[type=checkbox]').val();
                });
                that.selectRowId = selected[0];
            },
            dataBound:function(){
                that.targetObj.find("#inoutRecordlist").find("tr:gt(0)").unbind("dblclick");
                that.targetObj.find("#inoutRecordlist").find("tr:gt(0)").dblclick(function(e){
                    var grid = that.targetObj.find("#inoutRecordlist").data("kendoGrid");
                    var dataItem = grid.dataItem(grid.select());
                    //打开查看窗口
                    that.openRecorderWindow(dataItem["id"]);
                });
            }
        });
    },
    initOrz:function () {
        var that = this;
        // 加载组织结构
        JsonpAjax(baseApiPath + 'recordMarket/ztreeData', '', 'json', function(res){
            var setting = {
                view: {
                    showLine: true,
                    selectedMulti: false,
                    dblClickExpand: false,
                    showIcon: false
                },
                data: {
                    key:{
                        name: "organizationName"
                    },
                    simpleData: {
                        enable:true,
                        idKey: "organizationCode",
                        pIdKey: "parentCode",
                        rootPId: ""
                    }
                }

            };
            var organizationTree = that.targetObj.find('#organization-tree2').lonixFloat({
                source : res,
                setting : setting,
                searchField : 'organizationName',
                target : that.targetObj.find('#organization_text2'),
                primary: function (nodes) {
                    that.sysUtils.mvvmModel.set('orgName',nodes[0].organizationName);
                    that.sysUtils.mvvmModel.set('orgGpc',nodes[0].organizationTypeCode);
                    that.sysUtils.mvvmModel.set('orgCode',nodes[0].organizationCode);
                    that.targetObj.find('#organization-tree2').fadeUp();
                }
            });
        }, true);
    },
    findData : function (e) {
        var that = this;
        if (!isEmpty(e)) {
            that = $(e.target).data('that');
        }
        if(validityForm(that.targetObj)){
            var grid = that.targetObj.find('#inoutRecordlist').data('kendoGrid');
            var param = that.sysUtils.getBindDocJson(that.models.bindFieldArray);
            //转换时间格式
            if(isNotEmpt(param["beginTime"])){
                param["beginTime"] = kendo.toString(param["beginTime"],'yyyy-MM-dd HH:mm:ss');
            }
            if(isNotEmpt(param["endTime"])){
                param["endTime"] = kendo.toString(param["endTime"],'yyyy-MM-dd HH:mm:ss');
                param["endTime"] = param["endTime"].split(' ')[0]+' 23:59:59';
            }
            if(null != that.userInfo && !isEmpty(that.targetObj.find("#operatorId").val())){
                param["operatorId"] =  that.userInfo.id;
            }else if(!isEmpty(that.targetObj.find("#operatorId").val())){
                param["operatorId"] =  that.targetObj.find("#operatorId").val();
            }
            var dataT = {jsonParam : JSON.stringify(param)};
            var dataSource = that.sysUtils.getDataSource({url : baseApiPath + 'recordMarket/list', data : dataT, dataType : 'odata'});

            grid.setDataSource(dataSource);
        }

    },
    openRecorderWindow:function(id,isEdit){
        var that = this;
        var titles = "查看进出详情";
        that.editResult = null;
        that.isEdit = isEdit;
        var openwidonw = function(){
            that.editDiv = that.sysUtils.openWindow(that.editDiv,{
                title:titles,
                height:"680px",
                width:"945px",
                resizable:false,
                content:"views/parkLotCenter/recordMarket/inoutRecoderEdit.html"
            }, true);
        };
        if(true == isEdit){
            var checkid =null,gridid=null;
            var ids = new Array();
            that.targetObj.find('input[type="checkbox"][name="inoutRecord_template_id"]:checked').each(function (inx, itm) {
                ids.push($(itm).val());
            });
            if(isNotEmpt(ids)){
                if(ids.length>1){
                    return;
                }
                checkid=ids[0].split('_')[0];
                that.isEdit=ids[0].split('_')[2]==0?true:false;
            }
            var grid = that.targetObj.find("#inoutRecordlist").data("kendoGrid");
            var dataItem = grid.dataItem(grid.select());
            if(null == dataItem && null == checkid){
                notification({ title:"操作失败",message:"请选择至少一条需要矫正的记录!!"},'info');
                return;
            }else if(null != dataItem){
                gridid=dataItem["id"];
            }
            //打开查看窗口
            titles='矫正车辆车牌信息';

            if(isNotEmpt(checkid)){
                id=checkid;
            }else{
                id=gridid;
            }
        }
        var ajaxPost = function(){
            JsonpAjax(baseApiPath+"recordMarket/" + id,null,"json",function(result){
                window.showInoutRecodeView=result;
                openwidonw();
            });
        };
        ajaxPost();
    },
    updateStatus : function (e) {
        var that = this;
        if ( !isEmpty(e) ) {
            that = $(e.target).data('that');
        }
        notification({title : '提示', message : '此操作无法撤销，是否确认作废？'}, 'confirm', {
            callback : function () {
                var ids = new Array();
                that.targetObj.find('input[type="checkbox"][name="inoutRecord_template_id"]:checked').each(function (inx, itm) {
                    ids.push($(itm).val());
                });
                if ( isEmpty(ids) ){
                    notification({title : '提示', message : '请勾选需要作废的数据'}, 'info');
                    return;
                }
                var carNo = new Array(),newIds=new Array();
                for(var i=0,l=ids.length;i<l;i++){
                    var no = ids[i].split('_')[1],status=ids[i].split('_')[2];
                    if(status!='0'){
                        carNo.push(no)
                    }else{
                        newIds.push(ids[i].split('_')[0]);
                    }
                }
                if(carNo.length>0){
                    var tips = carNo.join(',')+'车牌进出记录状态非入场状态！';
                    notification({ title:"操作无效",message:tips},'info');
                    return;
                }
                var dataT = { ids : newIds.join(',') };
                JsonpAjax(baseApiPath + 'recordMarket/updateStatus', JSON.stringify(dataT), 'json', function (result) {
                    that.findData();
                }, true);
            }
        });
    },
}
